/*
 * Copyright 2007 Jeffrey Palm
 */

import java.io.IOException;
import java.io.Reader;

/**
 * A very inefficient version of Sun's BufferedReader.  But if
 * the underlying Reader is buffered this should be ok.
 */
public class BufferedReader {

  private final Reader in;
  
  public BufferedReader(final Reader in) {
    this.in = in;
  }

  public void close() throws IOException {
    in.close();
  }
  
  /**
   * We'll set this to an extra char that we read when
   * checking for an '\n' after an '\r'.  If it's -1 nothing 
   * was read.
   */
  private int extraChar = -1;
  
  public String readLine() throws IOException {
    
    // Our result
    StringBuffer buf = new StringBuffer();

    // First if we read an extra character and it wasn't
    // an '\n' we need to start with that
    if (extraChar != -1) buf.append((char)(extraChar & 0xff));
    
    // Exit value: If we exitted on a -1 set to true
    boolean exittedOnMinusOne = false;
    
    // Next read the rest
    for (;;) {
      int c = in.read();
      if (c == -1) {
        exittedOnMinusOne = true;
        break;
      }

      // if we have a \r let's try to pull off an \n
      // we have 3 choices for extraChar:
      //  -1 : leave it
      //  \n : turn to -1
      //   * : leave it, we'll get it next time
      if (c == '\r') {
        if ((extraChar = in.read()) == '\n') {
          extraChar = -1;
        }
        exittedOnMinusOne = false;
        break;
      } if (c == '\n') {
        exittedOnMinusOne = false;
        break;
      }
      
      // Now just append the char
      buf.append((char)(c & 0xff));
    }
    
    // If we exitted on a -1 make sure that the length is
    // > 0, if not return null;
    if (exittedOnMinusOne && buf.length() == 0) return null;
    
    // Return the result
    return buf.toString();
  }
}
